package com.dream.libx264;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class X264Sample {


    private int WIDTH = 1920;
    private final int HEIGHT = 1080;
    private final int FRAME_SIZE = WIDTH * HEIGHT * 3 / 2;

    public void test() throws Exception{

        long pts = 0;
        XH264Encoder encoder = new XH264Encoder(WIDTH,HEIGHT);
        String filePath = "/mnt/sdcard/cwt/1738908338941.yuv";
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在: " + filePath);
            return;
        }

        FileOutputStream out = new FileOutputStream("/mnt/sdcard/cwt/1234.h264");;

        encoder.setOnEncodedDataAvailableListener(new XH264Encoder.OnEncodedDataAvailableListener() {
            @Override
            public void onFormat(byte[] sps,byte[] pps) {
                try {
                    System.out.println("onFormat");
                    out.write(sps);
                    out.write(pps);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onEncodedDataAvailable(byte[] encodedData, long pts, boolean isIFrame) {
                try {
                    out.write(encodedData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[FRAME_SIZE];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                encoder.encodeFrame(buffer,pts+=1);
            }

            encoder.flushAndClose();//清空缓存区，可能还会输出好几帧
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
